package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import utile.Md5;
import model.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author lk
 * @create 2022-12-13 11:01
 */
@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符格式

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        System.out.println("deafasfa");
        //以字符流的形式接收数据
        BufferedReader reader = new BufferedReader(req.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }
        //将接收的数据转换为json对象方便后面获取
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //创建加密对象
        Md5 md5 = new Md5();

        //从json对象中以键值对的方式获取数据
        String username = jsonObject.getString("username");
        String password = md5.encryption(jsonObject.getString("password"));

        //获取session
        HttpSession session = req.getSession();

        User user = userService.login(username, password);

        //创建一个用来传数据的JSON对象
        JSONObject message = new JSONObject();
        //判断用户名或者密码是否错误
        if (user == null) {
            //状态0表示出错，1代表正确
            message.put("status", "0");
            message.put("Msg", "用户名或者密码错误");
            resp.getWriter().write(message.toString());
            return;
        }
        //将user加入到会话中
        session.setAttribute("user", user);
        //向前端发送正确的状态已经要跳转的页面
        message.put("status", "1");
        message.put("userMsg", user);
        resp.getWriter().write(message.toString());
    }
}
